// dbRemoteList.js
const path = require('path');
const sqlite3 = require('sqlite3').verbose();
const { JobsTable } = require('./tables/tableJobs');
const { TasksTable } = require('./tables/tableTasks');

class PipelineDB {
    constructor(app) {
        try {
            // 数据库基础信息
            this.app = app;
            this.userDataPath = app.userDataPath;
            this.dbPath = path.join(this.userDataPath, 'pipeline', 'pipeline.db');
            this.db = new sqlite3.Database(this.dbPath);

            // 创建并初始化具体的sqlite表
            this.jobs = new JobsTable(app, this.db);
            this.tasks = new TasksTable(app, this.db);
            this.init();

            // 如果没有异常，则初始化数据库成功
            console.log(`## Open PipelineDB OK [${this.dbPath}]`);
        } catch (error) {
            throw new Error('## Open PipelineDB Failed, Error: ' + error.message);
        }
    }

    init() {
        this.jobs && this.jobs.init();
        this.tasks && this.tasks.init();
    }

    async close() {
        return new Promise((resolve, reject) => {
            this.db.close((err) => {
                if (err) {
                    console.error('## Close PipelineDB Failed, Error: ', err);
                    reject(err);
                } else {
                    console.log('## Close PipelineDB OK!');
                    resolve();
                }
            });
        });
    }
}

module.exports = { PipelineDB };
